package com.rbac.controller;


import com.apis.login.LoginApis;
import com.common.aspect.AuthorityUtil;
import com.common.aspect.RedisEnum;
import com.common.utils.JwtUtil;
import com.domain.dto.login.LoginDto;
import com.domain.dto.login.MenuTreeDTO;
import com.domain.vo.JsonVO;
import com.domain.vo.login.CodeVo;
import com.domain.vo.login.LoginVo;
import com.domain.vo.login.PermissionListVO;
import com.rbac.pojo.User;
import com.rbac.service.ILoginService;
import com.wf.captcha.SpecCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Tag(name = "登录控制层")
@RestController
@RequestMapping("")
public class LoginController implements LoginApis {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AuthorityUtil authorityUtil;

    @Override
    @GetMapping("/get-menu/{userId}")
//    @Operation(summary = "查询用户菜单树")
    public JsonVO<List<MenuTreeDTO>> getMenuTree(@PathVariable Integer userId) {
        return JsonVO.success(loginService.getMenuTree(userId));
    }

    /**
     * 生成验证码
     * @return 返回前端图片和key：captcha+uuid
     */
    @GetMapping("/code")
    public JsonVO<CodeVo> code(){
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key ="captcha:" + UUID.randomUUID();
        redisTemplate.opsForValue().set(key, verCode, 30, TimeUnit.SECONDS);

        CodeVo loginVo = new CodeVo(specCaptcha.toBase64(), key);
        return JsonVO.success(loginVo);
    }

    @Operation(summary = "验证码登录")
//    @PostMapping("/login")
    public JsonVO<LoginVo> Login(@RequestBody @Validated LoginDto loginDto){
        //验证码获取并校验
        String redisCode = redisTemplate.opsForValue().get(loginDto.getKey());
        if (redisCode == null || !redisCode.equals(loginDto.getCode())) {
            throw new RuntimeException("验证码错误或已失效");
        }
        redisTemplate.delete(loginDto.getKey());
        //验证账号密码

        return JsonVO.success(loginService.checkLogin(loginDto));
    }

    @Operation(summary = "账号密码登录（无验证码）")
    @GetMapping("/login/{username}/{password}")
    public String login(@PathVariable String username, @PathVariable String password){
        User user = loginService.login(username, password);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        claims.put("username", user.getUsername());
        String token = JwtUtil.genToken(claims);
        System.out.println(token);
        String key = RedisEnum.Login_TOKEN_KEY.getPrefix() + token;
        redisTemplate.opsForValue().set(key, token, 30, TimeUnit.MINUTES);
        return token;
    }

    @Operation(summary = "获取权限列表")
    @GetMapping("/permission/{userId}")
    public PermissionListVO getPermissionList(@PathVariable Integer userId){
        List<String> permissionList = loginService.getPermsListByUserId(userId);
        System.out.println(permissionList);
        boolean addRow = authorityUtil.addAuth(userId, permissionList);
        if(!addRow){
            throw new RuntimeException("保存数据失败");
        }
        return new PermissionListVO(userId, permissionList);
    }
//    @PostMapping("/register")
//    public Result register(@RequestBody @Validated RegisterDto registerDto){
//        loginService.register(registerDto);
//        return Result.success("注册成功");
//    }

}
